package com.server.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.server.database.SQLCreator;
import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICommonDataService;
import com.server.service.IMsgManagementService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("MsgManagementService")
public class MsgManagementService implements IMsgManagementService {
	
	private final String msgTable = "education.message";
	private String requestUrl = null;
	
	@Override
	public String getRequestUrl() {
		return requestUrl;
	}
	@Override
	public void setRequestUrl(String requestUrl) {
		this.requestUrl = requestUrl;
	}
	/*
	 * 预推送消息
	 */
	private List<Map<String, Object>> prePushData = new ArrayList<Map<String,Object>>();
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	/**
	 * 获取未推送的消息列表
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@Override
	public void loadPushData(){
		String sql = "select distinct uuid,msgName,pushTime,state from %s where state=0";
		this.prePushData = jdbcTemplate.queryForList(String.format(sql, msgTable));
	}
	@Override
	public List<Map<String, Object>> getPrePushData() {
		return prePushData;
	}
	@Override
	public void addPrePushData(Map<String, Object> map){
		this.prePushData.add(map);
	}
	@Override
	public void updatePrePushData(String uuid,Map<String, Object> map){
		Iterator<Map<String, Object>> iterator = this.prePushData.iterator();
		Boolean continues = true;
		while(iterator.hasNext() && continues){
			Map<String, Object> next = iterator.next();
			Object uuidObj = next.get("uuid");
			if (uuid.equals(uuidObj)) {
				continues = false;
				this.prePushData.remove(next);
			}
		}
		this.prePushData.add(map);
	}
	@Override
	public void deletePrePushData(String uuid){
		Iterator<Map<String, Object>> iterator = this.prePushData.iterator();
		Boolean continues = true;
		while(iterator.hasNext() && continues){
			Map<String, Object> next = iterator.next();
			Object uuidObj = next.get("uuid");
			if (uuid.equals(uuidObj)) {
				continues = false;
				this.prePushData.remove(next);
			}
		}
	}
	 /**
	 * 调用自动消息推送的Http请求
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@Override
	public void autoPush(){
		if (this.prePushData == null || this.prePushData.size() < 1 
				|| StringUtils.isEmpty(requestUrl)) {
			return ;
		}
		
//System.out.println(requestUrl);
		String getURL = requestUrl+"msg/mng/autoPush";
        URL getUrl;
		try {
			getUrl = new URL(getURL);
			HttpURLConnection connection = (HttpURLConnection) getUrl
					.openConnection();
			connection.connect();
			// 取得输入流，并使用Reader读取
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			reader.close();
			
			// 断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	 /**
	 * 消息新增
	 * @param operator
	 * @param users
	 * @param inputMap
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月23日
	 */
	@Override
	public Integer add(String operator,
			List<String> users,Map<String, Object> inputMap){
		StringBuffer fieldBuffer = new StringBuffer("creater,createTime");
		StringBuffer valueBuffer = new StringBuffer();
		String dateStr = DateUtil.getDateStr(new Date(),
				DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		valueBuffer.append("'").append(operator).append("','").append(dateStr)
				.append("'");
		Set<String> keySet = inputMap.keySet();
		for (String key : keySet) {
			if ("creater".equals(key) || "createTime".equals(key)) {
				continue;
			}
			Object valueObj = inputMap.get(key);
			if (valueObj == null || StringUtils.isEmpty(valueObj.toString())) {
				continue;
			}
			fieldBuffer.append(",");
			fieldBuffer.append(key);
			valueBuffer.append(",");
			valueBuffer.append("'").append(valueObj).append("'");
		}
		Iterator<String> iterator = users.iterator();
		String[] sqls = new String[users.size()];
		int i = 0;
		while(iterator.hasNext()){
			StringBuffer sqlBuffer = new StringBuffer();
			String user = iterator.next();
			sqlBuffer.append("insert into ").append(msgTable).append("(")
			.append(fieldBuffer).append(",recipient").append(")").append(" values(")
			.append(valueBuffer).append(",'").append(user).append("'); ");
			sqls[i++] = sqlBuffer.toString();
		}
		int[] batchUpdate = jdbcTemplate.batchUpdate(sqls);
		return batchUpdate.length;
	}
	 /**
	 * 获取编制人的消息列表
	 * @param creater
	 * @param requestInput
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月23日
	 */
	@Override
	public DataVector<Map<String, Object>> getListByCreater (String creater,
			RequestInput requestInput){
		StringBuffer whereStr = new StringBuffer();
		whereStr.append("creater='").append(creater).append("'");
		String sortStr = "createTime desc";
		Integer pageIndex = 0;
		Integer pageSize = Integer.MAX_VALUE;
		if (requestInput != null) {
			if (requestInput.getWhereStr() != null
					&& requestInput.getWhereStr().length() > 0) {
				if (whereStr.length() > 0) {
					whereStr.append(" AND ");
				}
				whereStr.append("(").append(requestInput.getWhereStr())
						.append(")");
			}
			if (requestInput.getSortStr() != null
					&& requestInput.getSortStr().length() > 0) {
				sortStr = requestInput.getSortStr();
			}
			pageIndex = requestInput.getPageIndex();
			pageSize = requestInput.getPageSize();
		}
		String sqlCount = SQLCreator.getSqlCount(msgTable, whereStr.toString(), "uuid", true);
		String sql = SQLCreator.getSql_Mysql(pageIndex, pageSize, msgTable, whereStr.toString(), sortStr, "uuid,msgName,state,type,pushType,creater,createTime,pushTime,factPushTime", true);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		Integer count = jdbcTemplate.queryForObject(sqlCount, Integer.class);
		return new DataVector<Map<String, Object>>(list, count);
	}
	/**
	 * 获取接收人的消息列表
	 * @param creater
	 * @param userType
	 * @param requestInput
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月23日
	 */
	@Override
	public DataVector<Map<String, Object>> getListByUser (String recipient,
			RequestInput requestInput){
		StringBuffer whereStr = new StringBuffer();
		whereStr.append("recipient='").append(recipient).append("'");
		String sortStr = "factPushTime desc";
		return commonDataService.getListData(msgTable, whereStr.toString(), sortStr, requestInput);
	}
	/**
	 * 获取系统生成的消息列表
	 * @param creater
	 * @param msgType
	 * @param requestInput
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@Override
	public DataVector<Map<String, Object>> getListBySys (RequestInput requestInput){
		StringBuffer whereStr = new StringBuffer();
		whereStr.append("creater='system'");
		String sortStr = "createTime desc";
		Integer pageIndex = 0;
		Integer pageSize = Integer.MAX_VALUE;
		if (requestInput != null) {
			if (requestInput.getWhereStr() != null
					&& requestInput.getWhereStr().length() > 0) {
				if (whereStr.length() > 0) {
					whereStr.append(" AND ");
				}
				whereStr.append("(").append(requestInput.getWhereStr())
				.append(")");
			}
			if (requestInput.getSortStr() != null
					&& requestInput.getSortStr().length() > 0) {
				sortStr = requestInput.getSortStr();
			}
			pageIndex = requestInput.getPageIndex();
			pageSize = requestInput.getPageSize();
		}
		String sqlCount = SQLCreator.getSqlCount(msgTable, whereStr.toString(), "uuid", true);
		String sql = SQLCreator.getSql_Mysql(pageIndex, pageSize, msgTable, whereStr.toString(), sortStr, "uuid", true);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		Integer count = jdbcTemplate.queryForObject(sqlCount, Integer.class);
		return new DataVector<Map<String, Object>>(list, count);
	}
	 /**
	 * 获取消息推送人
	 * @param uuid
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@Override
	public List<String> getUsers(String uuid){
		List<String> userList = new ArrayList<String>();
		String sql = "select recipient from %s where uuid='%s'";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, msgTable,uuid));
		Iterator<Map<String, Object>> iterator = list.iterator();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			Object createrObj = next.get("recipient");
			if (createrObj != null) {
				userList.add(createrObj.toString());
			}
		}
		return userList;
	}
	 /**
	 * 设置消息状态为已推送并清除内存中的预推送消息
	 * @param uuid
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@Override
	public Integer updateState(String uuid){
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		StringBuffer updateStr = new StringBuffer("Update ");
		updateStr.append(msgTable).append(" set ").append("state=1,factPushTime='")
			.append(dateStr).append("' where uuid='").append(uuid).append("'");
		int update = jdbcTemplate.update(updateStr.toString());
		if(update > 0){
			this.deletePrePushData(uuid);
		}
		return update;
	}
	 /**
	 * 推送消息表单
	 * @param uuid
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月31日
	 */
	@Override
	public Map<String, Object> getForm(String uuid){
		String sql = "select * from %s where uuid='%s'";
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, msgTable,uuid));
		if (list.size() < 1) {
			return map;
		}
		map = list.get(0);
		Iterator<Map<String, Object>> iterator = list.iterator();
		StringBuffer uuidBuffer = new StringBuffer();
		StringBuffer userBuffer = new StringBuffer();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			Object uuidObject = next.get("recipient");
			if (uuidObject == null) {
				continue;
			}
			if (uuidBuffer.length() > 0) {
				uuidBuffer.append(",");
			}
			uuidBuffer.append(uuidObject.toString());
			Object userObject = next.get("recipientName");
			if (userObject == null) {
				continue;
			}
			if (userBuffer.length() > 0) {
				userBuffer.append(",");
			}
			userBuffer.append(userObject.toString());
		}
		map.put("uuids", uuidBuffer.toString());
		map.put("users", userBuffer.toString());
		return map;
	}
	@Override
	public Integer delete(String uuids,String operator){
		String sql = "delete from %s where uuid in('%s')";
		return jdbcTemplate.update(String.format(sql, msgTable, uuids.replaceAll(",", "','")));
	}
}
